import React, { useEffect, useState } from "react"
import { Drawer, Spin, Button } from "antd"
import { get } from "@/utils/request"
import { CheckStatusResp } from "@/models/result-item"
import styled from "styled-components"

interface ProgressDrawerProps {
  uuid: string
  visible: boolean
  onClose: () => void
}

const StyledLoading = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  height: 80vh;
  width: 100%;

  & > span {
    margin-left: 14px;
  }
`

const StyledFooterBtnGroup = styled.div`
  text-align: right;
  & > button {
    margin-left: 10px;
  }
`

export const ProgressDrawer: React.FC<ProgressDrawerProps> = ({
  uuid,
  visible,
  onClose,
}) => {
  const [statusInfo, setStatusInfo] = useState<CheckStatusResp>()

  useEffect(() => {
    if (!uuid) {
      return
    }

    const intervalHandle = setInterval(() => {
      get<CheckStatusResp>("/pegasus/api/status", { uuid })
        .then((res) => {
          setStatusInfo(res.data)
          if (res.data.state === "success") {
            clearInterval(intervalHandle)
          }
        })
        .catch(() => {
          clearInterval(intervalHandle)
        })
    }, 2000)
  }, [uuid])

  return (
    <Drawer
      visible={visible}
      maskClosable={false}
      onClose={onClose}
      title="生成进度"
      width={700}
      footer={
        <StyledFooterBtnGroup>
          <Button onClick={onClose}>关闭</Button>
          <Button type="primary" onClick={onClose}>
            确定
          </Button>
        </StyledFooterBtnGroup>
      }
    >
      {statusInfo?.state === "running" ? (
        <StyledLoading>
          <Spin />
          <span>正在生成中</span>
        </StyledLoading>
      ) : null}
      {statusInfo?.state === "success" ? (
        <div className="mt-5">
          <div className="flex">
            <span className="w-24 mr-5 inline-block text-right">uuid:</span>
            <span>{uuid}</span>
          </div>
        </div>
      ) : null}
      {!statusInfo?.state ? <div className="mt-5">Error</div> : null}
    </Drawer>
  )
}
